package com.yao2san.sim.storage.client.core.integrate;

import com.yao2san.sim.storage.client.config.IntegrateProperties;
import com.yao2san.sim.storage.client.core.enums.StorageType;
import com.yao2san.sim.storage.client.exception.StorageClientException;
import com.yao2san.sim.storage.client.core.api.response.ResponseCode;
import com.yao2san.sim.storage.client.core.api.response.ResponseData;
import com.yao2san.sim.storage.client.util.JSONUtil;
import com.yao2san.sim.storage.client.util.RequestUtil;
import lombok.Data;
import org.springframework.beans.BeanUtils;

import java.util.HashMap;
import java.util.Map;

import static com.yao2san.sim.storage.client.config.Constants.API_GET_CONFIG;

/**
 * 集成存储配置
 *
 * @author wxg
 **/
@Data
public class IntegrateConfig {
    /**
     * 存储类型
     */
    private StorageType storageType;
    /**
     * 存储服务地址
     */
    private String endpoint;

    /**
     * 区域
     */
    private String region;
    /**
     * 存储桶
     */
    private String bucket;
    /**
     * 根路径
     */
    private String path;

    /**
     * access key
     */
    private String ak;
    /**
     * secret key
     */
    private String sk;

    /**
     * 临时授权凭证有效期,单位:秒,默认30分钟
     */
    private Long stsDurationSeconds = 1800L;
    /**
     * 端口
     */
    private int port;

    /**
     * 文件映射前缀,仅当storageType=LOCAL时有效
     */
    private String prefix;

    /**
     * 角色,用于获取临时授权凭证,阿里OSS特有
     */
    private String roleArn;

    private IntegrateProperties integrateProperties;

    public IntegrateConfig() {

    }

    public IntegrateConfig(IntegrateProperties integrateProperties) {
        this.integrateProperties = integrateProperties;
        loadConfig();
    }

    @SuppressWarnings("unchecked")
    private synchronized void loadConfig() {
        String url = integrateProperties.getServer() + API_GET_CONFIG;
        String openId = integrateProperties.getOpenId();
        String secretKey = integrateProperties.getSecretKey();

        Map<String, Object> params = new HashMap<>(4);
        params.put("url", url);
        params.put("openId", openId);
        params.put("secretKey", secretKey);

        ResponseData<IntegrateConfig> responseData = null;
        responseData = RequestUtil.getForObject(url, params, ResponseData.class);
        fillConfig(responseData);
    }

    private void fillConfig(ResponseData<IntegrateConfig> responseData) {
        if (responseData == null) {
            throw new StorageClientException("Get storage config error!");
        }
        if (responseData.getCode() != ResponseCode.SUCCESS.getCode()) {
            throw new StorageClientException(responseData.getMsg());
        }
        IntegrateConfig config = JSONUtil.parseObject(JSONUtil.toJSONString(responseData.getData()), IntegrateConfig.class);
        BeanUtils.copyProperties(config, this,"integrateProperties");
    }
}
